/*
' Copyright (c) 2012 Pillars of God Academy
'  All rights reserved.
' 
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
' 
*/

using System;
using System.Web.UI.WebControls;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Security;
using DotNetNuke.Modules.CashBook.Components;
using DotNetNuke.Modules.CashBook.Data;
using DotNetNuke.Entities.Users;
using DotNetNuke.UI.Utilities;
using DotNetNuke.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Framework.Providers;
using System.Globalization;
using System.Data;
using iTextSharp.text;
using System.IO;
using iTextSharp.text.pdf;
using it = iTextSharp.text;
using System.Data.SqlClient;


namespace DotNetNuke.Modules.CashBook
{

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The View class displays the content
    /// 
    /// Typically your view control would be used to display content or functionality in your module.
    /// 
    /// View may be the only control you have in your project depending on the complexity of your module
    /// 
    /// Because the control inherits from CashBookModuleBase you have access to any custom properties
    /// defined there, as well as properties from DNN such as PortalId, ModuleId, TabId, UserId and many more.
    /// 
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class View : CashBookModuleBase, IActionable
    {

        #region Event Handlers

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
        }


        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// -----------------------------------------------------------------------------
        private void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    ENTRYPANEL.Visible = false;
                    ListPanel.Visible = false;
                }
                else
                {
                    ListPanel.Visible = true;
                }

            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// <summary>
        /// entrybutton_Click switches panel visibility
        /// and preloads transaction date
        /// </summary>
        /// 
        protected void entrybutton_Click(object sender, EventArgs e)
        {
            ListPanel.Visible = false;
            ENTRYPANEL.Visible = true;
            transdatetextbox.Text = DateTime.Now.ToShortDateString();
        }

        /// <summary>
        /// listbutton_Click switches panel visibility
        /// and preloads transaction totals
        /// </summary>
        protected void listbutton_Click(object sender, EventArgs e)
        {
            ENTRYPANEL.Visible = false;
            ListPanel.Visible = true;
            var tot = CashLineController.TotalCashBook(ModuleId);
            if (tot != null)
            {
                    TotalInlbl.Text = tot.TotalIn.ToString("N", NumberFormatInfo.CurrentInfo);
                    TotalOutlbl.Text = tot.TotalOut.ToString("N", NumberFormatInfo.CurrentInfo);
                    Balancelbl.Text = Convert.ToSingle(tot.Balance).ToString("N", NumberFormatInfo.CurrentInfo);
            }
            CashBookList.DataSource = CashLineController.GetCashBook(ModuleId);
            CashBookList.DataBind();
        }

        /// <summary>
        /// numrows_OnTextChanged switches page size
        /// based on user input
        /// </summary>
        protected void numrows_OnTextChanged(object sender, EventArgs e)
        {
            CashBookPager.PageSize = Convert.ToInt32(numrowstxtbox.Text);
            listbutton_Click(sender, e);
        }

        /// <summary>
        /// submitbutton_Click saves transaction input
        /// and reloads base page
        /// </summary>
        protected void submitbutton_Click(object sender, EventArgs e)
        {
            CashLine t;

            if (LineId > 0)
            {
                t = CashLineController.GetCashLine(LineId);
                t.TransDate = DateTime.Parse(transdatetextbox.Text);
                t.WhoFrom = whofromtextbox.Text.Trim();
                t.WhoTo = whototextbox.Text.Trim();
                t.Reason = reasontextbox.Text.Trim();
                t.WhoFor = whofortextbox.Text.Trim();
                t.AmountIn = Convert.ToSingle(amtintextbox.Text.Trim());
                t.AmountOut = Convert.ToSingle(amtouttextbox.Text.Trim());
                t.Posted = false;
                t.ModuleId = ModuleId;
                t.LastModifiedByUserId = UserId;
                t.LastModifiedOnDate = DateTime.Now;
            }
            else
            {
                t = new CashLine
                {
                    TransDate = DateTime.Parse(transdatetextbox.Text.Trim()),
                    WhoFrom = whofromtextbox.Text.Trim(),
                    WhoTo = whototextbox.Text.Trim(),
                    Reason = reasontextbox.Text.Trim(),
                    WhoFor = whofortextbox.Text.Trim(),
                    AmountIn = amtintextbox.Text != "" ? Convert.ToSingle(amtintextbox.Text.Trim()) : Convert.ToSingle("0.00"),
                    AmountOut = amtouttextbox.Text != "" ? Convert.ToSingle(amtouttextbox.Text.Trim()) : Convert.ToSingle("0.00"),
                    Posted = false,
                    ModuleId = ModuleId,
                    CreatedByUserId = UserId,
                    CreatedOnDate = DateTime.Now,
                    LastModifiedByUserId = UserId,
                    LastModifiedOnDate = DateTime.Now
                };
            }

            CashLineController.SaveCashLine(t, TabId);
            Response.Redirect(DotNetNuke.Common.Globals.NavigateURL());
        }

        /// <summary>
        /// cancelbutton_Click abandons transaction entry
        /// and reloads base page
        /// </summary>
        protected void cancelbutton_Click(object sender, EventArgs e)
        {            
            Response.Redirect(DotNetNuke.Common.Globals.NavigateURL());
        }


        /// <summary>
        /// prtbutton_OnClick runs itextsharp
        /// PDF creator
        /// </summary>
        protected void prtButton_OnClick(object sender, EventArgs e)
        {
            // Create a Document object
            var document = new Document(PageSize.A4, 50, 50, 50, 50);

            // Create a new PdfWriter object, specifying the output stream
            var output = new MemoryStream(); // FileStream(Server.MapPath("MyFirstPDF.pdf"), FileMode.Create);
            var writer = PdfWriter.GetInstance(document, output);

            // Open the Document for writing
            document.Open();

            var titleFont = FontFactory.GetFont("Arial", 18, Font.BOLD);
            var subTitleFont = FontFactory.GetFont("Arial", 14, Font.BOLD);
            var boldTableFont = FontFactory.GetFont("Arial", 8, Font.BOLD);
            var endingMessageFont = FontFactory.GetFont("Arial", 8, Font.ITALIC);
            var bodyFont = FontFactory.GetFont("Arial", 8, Font.NORMAL);
            var smallfont = FontFactory.GetFont("Arial", 7, Font.ITALIC);

            document.Add(new Paragraph("CashBook Detail Report", titleFont));

            var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("/Portals/" + PortalId.ToString() + "/" + PortalSettings.LogoFile.ToString()));
            logo.SetAbsolutePosition(280, 770);
            logo.ScaleAbsoluteWidth(240);
            document.Add(logo);

            var outTable = new PdfPTable(8);
            PdfPCell cell = new PdfPCell(new Phrase("CashBook", subTitleFont));
            cell.Colspan = 8;
            outTable.TotalWidth = 490f;
            //fix the absolute width of the table
            outTable.LockedWidth = true;
            //relative col widths in proportions
            float[] widths = new float[] { 0.4f, 1f, 1f, 1f, 2.8f, 1f, 0.9f, 0.9f };
            outTable.SetWidths(widths);
            outTable.HeaderRows = 2;
            cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
            outTable.SpacingBefore = 30f;
            outTable.SpacingAfter = 10f;
            outTable.AddCell(cell);
            outTable.AddCell(new Phrase("Num", boldTableFont));
            outTable.AddCell(new Phrase("Transaction Date", boldTableFont));
            outTable.AddCell(new Phrase("From", boldTableFont));
            outTable.AddCell(new Phrase("To", boldTableFont));
            outTable.AddCell(new Phrase("Reason for payment", boldTableFont));
            outTable.AddCell(new Phrase("Department", boldTableFont));
            outTable.AddCell(new Phrase("Amount In", boldTableFont));
            outTable.AddCell(new Phrase("Paid Out", boldTableFont));
          
            //string connect = DataProvider.GetConnection().ConnectionString;


            //using (SqlConnection conn = new SqlConnection(connect))
            {
            //    string query = "SELECT * from " + {databaseOwner} + "[" + {objectQualifier}  + "Cashbook]";
            //    SqlCommand cmd = new SqlCommand(query, conn);
                try
                {
            //        conn.Open();
            //        using (SqlDataReader rdr = cmd.ExecuteReader())
                    using (IDataReader rdr = DataProvider.Instance().GetCashBook(ModuleId))
                    {
                        while (rdr.Read())
                        {
                            outTable.AddCell(new Phrase(rdr[0].ToString(), bodyFont));
                            DateTime transdate = DateTime.Parse(rdr[1].ToString());
                            string transdate2 = transdate.ToShortDateString();
                            outTable.AddCell(new Phrase(transdate2, bodyFont));                           
                            outTable.AddCell(new Phrase(rdr[2].ToString(), bodyFont));
                            outTable.AddCell(new Phrase(rdr[3].ToString(), bodyFont));
                            outTable.AddCell(new Phrase(rdr[4].ToString(), bodyFont));
                            outTable.AddCell(new Phrase(rdr[5].ToString(), bodyFont));
                            PdfPCell inCell = new PdfPCell(new Phrase(rdr[7].ToString().Remove(rdr[7].ToString().Length - 2), bodyFont));
                            inCell.HorizontalAlignment = 2;
                            outTable.AddCell(inCell);
                            PdfPCell outCell = new PdfPCell(new Phrase(rdr[6].ToString().Remove(rdr[6].ToString().Length - 2), bodyFont));
                            outCell.HorizontalAlignment = 2;
                            outTable.AddCell(outCell);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
                document.Add(outTable);
                // Add footer after the last row of the table
                Paragraph footer = new Paragraph("CashBook, a DNN Module from Pillars of God Academy, Bacoor, Philippines - Copyright 2012", smallfont);
                document.Add(footer);
                // Close the Document - this saves the document contents to the output stream
                document.Close();

                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename=CashBook-{0}.pdf", DateTime.Now.ToShortDateString()));
                Response.BinaryWrite(output.ToArray()); 
            }
        }

        #endregion

        #region Optional Interfaces

        public ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection Actions = new ModuleActionCollection();
                Actions.Add(GetNextActionID(), Localization.GetString("EditModule", this.LocalResourceFile), "", "", "", EditUrl(), false, SecurityAccessLevel.Edit, true, false);
                return Actions;
            }
        }

        #endregion


    }
}
